<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-button icon="el-icon-plus" style="margin-bottom:20px" type="primary" size="mini" @click="addRole(1)">新增角色</el-button>
        <el-table border :data="RoleList" style="width: 100%">
          <el-table-column align="center" prop="title" label="角色名称" />
          <el-table-column align="center" prop="description" label="角色描述" />
          <el-table-column align="center" label="操作">
            <template #default="{row}">
              <el-button size="small" type="primary" @click="editRole(2,row.id)">分配权限</el-button>
              <el-button size="small" @click="editRole(1,row.id)">编辑</el-button>
              <el-button size="small" type="danger" @click="delRole(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          style="margin-top:20px;text-align:center"
          :current-page="currentPage"
          :page-sizes="[5, 10, 15, 20]"
          layout="total, sizes, prev, pager, next, jumper"
          :page-size="roleparams._limit"
          :total="total"
          @size-change="SizeChange"
          @current-change="changeCurrent"
        />
        <!-- 弹窗 -->
        <el-dialog :title="roleForm.id?'编辑角色':'新增角色'" :visible="isShowDialog" @close="btnCanCel">
          <el-form ref="roleForm" :model="roleForm" :rules="rules">
            <el-form-item prop="title" label="角色名称" label-width="120px">
              <el-input ref="Role" v-model.trim="roleForm.title" autocomplete="off" />
            </el-form-item>
            <el-form-item prop="description" label="角色描述" label-width="120px">
              <el-input v-model.trim="roleForm.description" autocomplete="off" />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="btnCanCel">取 消</el-button>
            <el-button type="primary" @click="btnOk">确 定</el-button>
          </div>
        </el-dialog>
        <!-- 权限弹窗 -->
        <el-dialog title="分配角色权限" :visible="assignDialog" @close="btnCanCel">
          <el-checkbox-group v-model="assignList">
            <el-tree
              :data="limitList"
              default-expand-all
              :expand-on-click-node="false"
              highlight-current
              :props="{label: 'title'}"
            >
              <template #default="{data}">
                <el-checkbox :label="data.id">{{ data.title }}</el-checkbox>
              </template>
            </el-tree>
          </el-checkbox-group>
          <div slot="footer" class="dialog-footer">
            <el-button @click="btnCanCel">取 消</el-button>
            <el-button type="primary" @click="btnOk">确 定</el-button>
          </div>
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
import { getRoleList, getCount, editRole, getRole, addRole, delRole } from '@/api/role'
import { listToTreeData } from '@/utils'
import { getLimitsList } from '@/api/limits'
export default {
  data() {
    return {
      RoleList: [],
      roleparams: {
        _limit: 5,
        _start: 0
      },
      total: 0,
      currentPage: 1,
      isShowDialog: false,
      assignDialog: false,
      isAssign: 1,
      limitList: [],
      assignList: [],
      roleForm: {
        id: '',
        title: '',
        description: ''
      },
      rules: {
        title: [{ required: true, message: '该项不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '该项不能为空', trigger: 'blur' }]
      }
    }
  },
  async created() {
    this.getRoleList()
    this.assignLimits = await getLimitsList({ _limit: 999, _start: 0 })
    this.limitList = listToTreeData(this.assignLimits, '0')
  },
  methods: {
    SizeChange(val) {
      this.roleparams._limit = val
      this.getRoleList()
    },
    changeCurrent(val) {
      this.roleparams._start = (val - 1) * this.roleparams._limit
      this.currentPage = val
      this.getRoleList()
    },
    async getRoleList() {
      this.RoleList = await getRoleList(this.roleparams)
      this.total = await getCount()
    },
    addRole(assign) {
      this.isAssign = assign
      this.isShowDialog = true
    },
    async editRole(assign, id) {
      this.isAssign = assign
      this.roleForm = await getRole(id)
      // 编辑
      if (assign === 1) {
        this.isShowDialog = true
      } else {
        // 分配权限功能
        this.assignList = this.roleForm.permissions.map(item => {
          return item.id
        })

        this.assignDialog = true
      }
    },
    async delRole(id) {
      try {
        await this.$confirm('此操作将永久删除, 是否继续?', '温馨提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        })
        await delRole(id)
        console.log(this.RoleList.length)
        // 当数组中长度为1同时当前页大于1时，当前页减一，确保当前页的数据都删除后，当前页码后退一页
        if (this.RoleList.length === 1 && this.currentPage > 1) {
          this.currentPage--
          this.roleparams._start = (this.currentPage - 1) * this.roleparams._limit
        }
        this.getRoleList()
        this.$message.success({
          message: '删除成功！',
          center: true
        })
      } catch (error) {
        return error
      }
    },
    async btnOk() {
      // 非分配权限弹窗
      if (this.isAssign !== 2) {
        try {
          await this.$refs.roleForm.validate()
          if (this.roleForm.id) {
            // 编辑
            await editRole(this.roleForm)
            this.$message.success({
              message: '编辑角色成功',
              center: true
            })
          } else {
            // 新增
            await addRole(this.roleForm)
            this.$message.success({
              message: '新增角色成功',
              center: true
            })
          }
          this.isShowDialog = false
        } catch (error) {
          return error
        }
      } else {
        // 分配权限的弹窗
        const arr = this.assignLimits.filter(item => {
          return this.assignList.includes(item.id)
        })
        await editRole({ ...this.roleForm, permissions: arr })
        this.assignDialog = false
        this.$message.success({
          message: '修改权限成功',
          center: true
        })
      }

      this.getRoleList()
    },
    btnCanCel() {
      this.roleForm = {
        id: '',
        title: '',
        description: ''
      }
      if (this.isAssign !== 2) {
        this.$refs.roleForm.resetFields()
        this.isShowDialog = false
      } else {
        this.assignList = []
        this.assignDialog = false
      }
    }
  }
}
</script>

<style>

</style>
